package com.gee.spring.boot.starter.opengemini.core.query.segment;


import com.gee.spring.boot.starter.opengemini.core.domain.ColumnInfo;
import com.gee.spring.boot.starter.opengemini.core.enums.AndOr;
import com.gee.spring.boot.starter.opengemini.core.enums.Condition;
import com.gee.spring.boot.starter.opengemini.core.util.TimeUtil;

import java.time.LocalDateTime;

import static com.gee.spring.boot.starter.opengemini.core.constant.StrConstant.SINGLE_QUOTE;
import static com.gee.spring.boot.starter.opengemini.core.constant.StrConstant.SPACE;


/**
 * @author gepengjun
 * @since 2024/4/28 8:55
 */
public class ConditionSegment implements IConditionSegment {

    private AndOr andOr;
    private final ColumnInfo columnInfo;
    private final Condition condition;
    private final Object value;

    public ConditionSegment(AndOr andOr, ColumnInfo columnInfo, Condition condition, Object value) {
        this.andOr = andOr;
        this.columnInfo = columnInfo;
        this.condition = condition;
        this.value = value;
    }

    @Override
    public String getSqlSegment() {
        String column = columnInfo.getColumn();
        StringBuilder sqlSegment = new StringBuilder();
        if (andOr != null){
            sqlSegment.append(andOr.getKeyWord());
        }
        sqlSegment.append(SPACE).append(column)
                .append(SPACE)
                .append(condition.getKeyWord())
                .append(SPACE);
        if (columnInfo.getTagFlag() || value instanceof String){
            sqlSegment.append(SINGLE_QUOTE)
                    .append(value.toString())
                    .append(SINGLE_QUOTE)
                    ;
        }else if (value instanceof LocalDateTime){
            LocalDateTime localDateTime = (LocalDateTime) value;
            sqlSegment.append(TimeUtil.timeToNanos(localDateTime))
            ;
        } else {
            sqlSegment.append(value)
                    ;
        }
        return sqlSegment.toString();
    }

    @Override
    public void setAndOr(AndOr andOr) {
        this.andOr = andOr;
    }
}
